﻿<?php
/*
*自定义日历表
*
*date 2016-06-09
*/
class MCalendar{
    private $month;//当前的月份
    private $year;//当前的年份
    private $days;//当前月的天数
    private $start_weekday;//当前月份的第一天对应的是周几
    private $end_weekday;//当前月份的最后一天对应的是周几
    private $total_box = 42;//总显示天数格子
    private $pre_month;//上个月的月份
    private $pre_year;//上个年份
    private $pre_month_days;//上个月总天数
    private $pre_month_days_count;//上个月要显示的天数总数
    private $next_month_days_count;//下个月要显示的天数总数
    private $calendar_str = "";
    //初始化
    function __construct(){
        $this->month = date("m");
        $this->year = date("Y");
        $this->days = date("t",strtotime("$this->year-$this->month-01"));
        $this->start_weekday = date("w",mktime(0,0,0,$this->month,1,$this->year)); 
        $this->end_weekday = date("w",mktime(0,0,0,$this->month,$this->days,$this->year)); 
        if($this->month == 1){//如果当前是1月份
            $this->pre_month = 12;
            $this->pre_year = $this->year -1;
        }else{
            $this->pre_month = $this->month -1;
            $this->pre_year = $this->year;
        }
        $date_str = $this->pre_year."-".$this->pre_month."-01";
        $this->pre_month_days = date("t",strtotime($date_str));
        $this->pre_month_days_count = $this->start_weekday == 0 ? 7 : $this->start_weekday;
        $this->next_month_days_count = $this->total_box - $this->pre_month_days_count - $this->days;
    }
    //显示日历
    function display(){
        $this->daysList();
        return $this->calendar_str;
    }
    //显示天数	
   private function daysList(){
        //输出上个月天数
        for($b=0; $b<$this->pre_month_days_count; $b++){
            $day = ($this->pre_month_days-$this->pre_month_days_count+$b+1);
            $this->calendar_str .= "<li><a href='javascript:void(0);' class='pre-month-day".($day < 10 ? "0".$day : $day)." pre-month'>".$day."</a></li>";
        } 
        //输出当前月天数
        for($d=1; $d<=$this->days; $d++){
            $b++;
            if($d == date("d")){
                $this->calendar_str .= "<li><a href='javascript:void(0);' style='color:red;' class='current-month-day".($d < 10 ? "0".$d : $d)." current-month today'>".$d."</a></li>";
            }
            else{
                $this->calendar_str .= "<li><a href='javascript:void(0);' class='current-month-day".($d < 10 ? "0".$d : $d)." current-month'>".$d."</a></li>";	 
            }	 
        }
        $c = 0;
        //输出下个月天数
       for($d=1; $d<= $this->next_month_days_count; $d++){
            $c++;
            $this->calendar_str .= "<li><a href='javascript:void(0);' class='next-month-day".($d < 10 ? "0".$d : $d)." next-month'>".$d."</a></li>";	 
       }
    }
}